extends Node
class_name ToolExecutor

signal tool_result(data: Dictionary)

func call_tool(function_name: String, arguments: Dictionary) -> void:
	if function_name == "_call_get_baike_info":
		_call_get_baike_info(arguments)
	else:
		emit_signal("tool_result", {"error": "Unknown function"})



func _call_get_baike_info(args: Dictionary) -> void:
	print(args)
	var words: String = args.get("words", "")
	
	print(words)
	
	# 写死的用户ID和KEY
	var id := "10004959"
	var key := "be2df23d61771de18e0b679f529cf5ae"
	
	if words == "":
		emit_signal("tool_result", {"error": "Missing required parameter 'words'"})
		return

	var base_url := "https://cn.apihz.cn/api/zici/baikebaidu.php"
	var query_string := "?id=" + id.uri_encode() + "&key=" + key.uri_encode() + "&words=" + words.uri_encode()
	var url := base_url + query_string

	var http := HTTPRequest.new()
	add_child(http)
	http.request_completed.connect(_on_baike_request_completed)
	var err := http.request(url, [], HTTPClient.METHOD_GET)
	print("HTTPRequest start err:", err)
	if err != OK:
		emit_signal("tool_result", {"error": "HTTPRequest failed to start: " + str(err)})

func _on_baike_request_completed(result: int, response_code: int, headers: Array, body: PackedByteArray) -> void:
	# 这里用 signal 的参数传递 http 对象
	var http = self  # 绑定时传入的 http 实例
	if http:
		http.queue_free()

	if result != HTTPRequest.RESULT_SUCCESS or response_code != 200:
		emit_signal("tool_result", {"error": "Request failed with code: " + str(response_code)})
		return

	var json_parser = JSON.new()
	var parse_err = json_parser.parse(body.get_string_from_utf8())
	if parse_err != OK:
		emit_signal("tool_result", {"error": "Failed to parse JSON"})
		return

	var data = json_parser.get_data()
	if typeof(data) == TYPE_DICTIONARY:
		if data.has("code") and data["code"] == 200:
			var msg = data.get("msg", "")
			emit_signal("tool_result", {"msg": msg})
		else:
			var err_msg = data.get("msg", "Unknown error")
			emit_signal("tool_result", {"error": err_msg})
	else:
		emit_signal("tool_result", {"error": "Invalid response format"})
